package com.asit.demo.config;

import com.asit.demo.model.User;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.asit.demo.mapper.UserMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Component
@Slf4j
@Data
@ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.salve")
public class DynamicDatasource {
    private String url;
    private String username;
    private String password;
    //动态数据源
    @Autowired
    protected DataSource dataSource;
    //数据源创建器
    @Resource
    protected DataSourceCreator dataSourceCreator;

    @Resource
    UserMapper userMapper;

    //创建数据源
    public void createNewDataSource() {
        DynamicRoutingDataSource drds = (DynamicRoutingDataSource) dataSource;
        DataSourceProperty dsp = new DataSourceProperty();
        dsp.setPoolName("salve");//链接池名称
        /*dsp.setUrl("jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&useSSL=false&characterEncoding=UTF-8&serverTimeZone=GMT%2B8");//数据库连接
        dsp.setUsername("root");//用户名
        dsp.setPassword("root");//密码*/
        dsp.setUrl(url);//数据库连接
        dsp.setUsername(username);//用户名
        dsp.setPassword(password);//密码
        dsp.setDriverClassName("com.mysql.cj.jdbc.Driver");//驱动
        if(!drds.getCurrentGroupDataSources().containsKey("salve1")){
            //创建数据源并添加到系统中管理
            DataSource dataSource = dataSourceCreator.createDataSource(dsp);
            drds.addDataSource("salve1", dataSource);
        }
    }


    //手动切换数据源
    public User demo(UserMapper mapper, Integer id) {
        DynamicDataSourceContextHolder.push("salve1");//数据源名称
        User user = null;
        try {
            // your code 需注意使用后一定要使用poll清空数据源，
            user = mapper.selectById(id);
        } catch (Exception e) {
            log.error("{}",e);
        } finally {
            DynamicDataSourceContextHolder.poll();
        }
        return user;
    }

}
